package cn.com.db.service;

import cn.com.db.model.Address;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressService extends BaseService{

    public void createAddress(Address address){
        if (address.getDef()){
            disDefAddress(address.getUser());
        }
        addressDao.createAddress(address);
    }

    public Address getAddressById(String id){
        return addressDao.getAddressById(id);
    }

    public Address getUserDefAddress(String userId){
        return addressDao.getUserDefAddress(userId);
    }

    public List<Address> getUserAddress(String userId,Integer count,Integer page){
        return addressDao.getUserAddress(userId,(count-1)*page,page);
    }

    public Integer countUserAddress(String userId){
        return addressDao.countUserAddress(userId);
    }

    @Transactional
    public void updateAddress(Address address){
        if (address.getDef()){
            disDefAddress(address.getUser());
        }
        addressDao.update(address);
    }

    @Transactional
    public void deleteAddress(String id){
        addressDao.delete(id);
    }


    @Transactional
    public void disDefAddress(String userId){
        Address address=addressDao.getUserDefAddress(userId);
        if (address==null){
            return;
        }
        address.setDef(false);
        addressDao.update(address);
    }

}
